//
//  MSProgressBar.m
//  MagicSword
//
//  Created by Netease on 15/11/25.
//  Copyright © 2015年 Jonear. All rights reserved.
//

#import "MSProgressBar.h"

@implementation MSProgressBar {
    CGFloat _toProgress;
    NSTimer *_timer;
    
    MSCompletionBlock _block;
    BOOL _isBlood;
}

//CGSizeMake(80, 15.0)
- (instancetype)initWithSize:(CGSize)size {
    self = [super initWithSize:size
               backgroundColor:[UIColor darkGrayColor]
                     fillColor:[UIColor colorWithRed:2.0/255.0 green:124.0/255.0 blue:34.0/255.0 alpha:1.0]
                   borderColor:[UIColor lightGrayColor]
                   borderWidth:2.0
                  cornerRadius:size.height/2];
    if (self) {
        
    }
    return self;
}

- (void)setProgress:(CGFloat)progress {
    [self setProgress:progress isBlood:YES];
}

- (void)setProgress:(CGFloat)progress isBlood:(BOOL)isBlood {
    _isBlood = isBlood;
    if (isBlood) {
        if (progress > 0.5) {
            [self setFillColor:UIColorFromRGB(0x0b9c1f)];
        } else if(progress>0.3) {
            [self setFillColor:UIColorFromRGB(0xdac515)];
        } else {
            [self setFillColor:UIColorFromRGB(0xe23007)];
        }
    } else {
        [self setFillColor:UIColorFromRGB(0x0b9c1f)];
    }
    
    [super setProgress:progress];
}

- (void)setProgressWithAniamtion:(CGFloat)progress completion:(MSCompletionBlock)block {
    _block = [block copy];
    if (self.progress != progress) {
        _toProgress = progress;
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    } else {
        [self performSelector:@selector(finishAniamtion) withObject:nil afterDelay:0.3];
    }
}

- (void)updateProgress {
    if (_toProgress == self.progress) {
        [_timer invalidate];
        _timer = nil;
        [self performSelector:@selector(finishAniamtion) withObject:nil afterDelay:0.3];
    }
    
    if (ABS(_toProgress-self.progress) < 0.04) {
        _toProgress = self.progress;
        [self setProgress:_toProgress isBlood:_isBlood];
    } else if (_toProgress > self.progress) {
        [self setProgress:self.progress+0.04 isBlood:_isBlood];
    } else{
        [self setProgress:self.progress-0.04 isBlood:_isBlood];
    }
}

- (void)finishAniamtion {
    if (_block) {
        _block();
//        _block = nil;
    }
}

@end
